package com.gzdh.tang.dishrecognition.job;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePayRequest;
import com.alipay.api.response.AlipayTradePayResponse;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.gzdh.tang.config.ali.AliPayUtil;
import com.gzdh.tang.modu.entity.*;
import com.gzdh.tang.modu.model.dk.JsonsRootBean;
import com.gzdh.tang.modu.service.*;
import com.gzdh.tang.modu.util.DateUtil;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 刷脸代扣
 */
@Component
@Slf4j
public class DrAliFaceAgreementJob {
    @Autowired
    AliFaceOrdersService aliFaceOrdersService;

    @Autowired
    FkService fkService;

    @Autowired
    ReserveService reserveService;

    @Autowired
    MacMainpSbruanService macMainpSbruanService;

    @Autowired
    ReserveXfjTempService reserveXfjTempService;


    @Autowired
    MacMainpSbruanDinnerService macMainpSbruanDinnerService;

    private List<MacMainpSbruan> macMainpSbruanList;

    @XxlJob("DrAliFaceAgreementJobHandler")
    public void DrAliFaceAgreementJobHandler() throws Exception {
        macMainpSbruanList = macMainpSbruanService.list();
        //将未上传的数据筛选出来
        List<AliFaceOrders> aliFaceOrdersList = aliFaceOrdersService.list(
                new QueryWrapper<AliFaceOrders>().lambda().eq(AliFaceOrders::getHavePost, false)
                        .eq(AliFaceOrders::getType, 1)
        );
        for (AliFaceOrders goo : aliFaceOrdersList) {
            tAliFaceOrder(goo);
        }
    }

    private void tAliFaceOrder(AliFaceOrders aliFaceOrders) {
        MacMainpSbruan macMainpSbruan = macMainpSbruanService
                .getOne(new QueryWrapper<MacMainpSbruan>().lambda().eq(MacMainpSbruan::getMac, aliFaceOrders.getDeviceId()));
        try {
            String dinner = getDinner(macMainpSbruan).trim();
            macMainpSbruan.setDinner(dinner);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("餐次获取失败");
        }

        Fk fk = fkService.getOne(new QueryWrapper<Fk>().lambda().eq(Fk::getCardno, aliFaceOrders.getCardno()));


        AlipayTradePayResponse response = null;
        if (StringUtils.isNotEmpty(aliFaceOrders.getAuthCode())) {
            response = havePost(aliFaceOrders.getOrders(),
                    aliFaceOrders.getPrice(), aliFaceOrders.getAuthCode(),
                    aliFaceOrders.getAliAgreementNo(), aliFaceOrders.getFkPrice(), aliFaceOrders.getTerminalParams(), aliFaceOrders.getAliToken());
            assert response != null;
            if (response.isSuccess()) {
//                throw new RuntimeException("支付失败");
                if (response.getEnterprisePayInfo().getIsUseEnterprisePay()) {
                    writeReserve(aliFaceOrders.getOrders(), "0");
                } else {
                    //未使用企业付，扣支付宝费用
//                    reserveService.insertReserve(macMainpSbruan.getMac(), aliFaceOrders.getOrders(),
//                            new BigDecimal(aliFaceOrders.getPrice()).multiply(new BigDecimal(100)).intValue(),
//                            1, fk, macMainpSbruan, "现金菜", macMainpSbruan.getCode(),
//                            new BigDecimal(aliFaceOrders.getPrice()), "4", aliFaceOrders.getOrders(), new Date());
                    writeReserve(aliFaceOrders.getOrders(), "4");
                }
            } else {
                writeReserve(aliFaceOrders.getOrders(), "-1");
//                saveReserve(aliFaceOrders, fk, macMainpSbruan, aliFaceOrders.getPrice(), "0");

//                System.out.println("【" + aliFaceOrders.getCardno() + "】支付失败：" + response.toString());
//                reserveService.insertReserve(macMainpSbruan.getMac(), aliFaceOrders.getOrders(),
//                        new BigDecimal(aliFaceOrders.getPrice()).multiply(new BigDecimal(100)).intValue(),
//                        1, fk, macMainpSbruan, "现金菜", macMainpSbruan.getCode(),
//                        new BigDecimal(aliFaceOrders.getPrice()), "0", aliFaceOrders.getOrders(), new Date());
            }
        }

//        if (new BigDecimal(fk.getKye()).compareTo(new BigDecimal(0)) == 1) {
//            aliFaceOrders.setFkPrice(new BigDecimal(fk.getKye()).setScale(2, BigDecimal.ROUND_HALF_UP).toString());
//        } else {
//            aliFaceOrders.setFkPrice("0");
//        }
//        aliFaceOrdersService.updateById(aliFaceOrders);


        aliFaceOrders.setHaveState(true);
        aliFaceOrders.setHavePost(true);
        aliFaceOrdersService.updateById(aliFaceOrders);
    }

    private void writeReserve(String orders, String sc) {
        List<ReserveXfjTemp> reserveXfjTempList = reserveXfjTempService.list(
                new QueryWrapper<ReserveXfjTemp>().lambda().eq(ReserveXfjTemp::getLsh2, orders)
        );
        List<Reserve> reserveList = new ArrayList<>();
        for (ReserveXfjTemp goo : reserveXfjTempList) {
            Reserve reserve = new Reserve();
            BeanUtils.copyProperties(goo, reserve);
            if ("4".equals(sc)) {
                reserve.setSc("4");
            } else if ("-1".equals(sc)) {
                reserve.setSc("0");
            }
            reserveList.add(reserve);
        }
        reserveService.saveBatch(reserveList);
    }

    private String getDinner(MacMainpSbruan macMainpSbruan) throws Exception {
        String hourMin = new SimpleDateFormat("HH:mm").format(new Date());
        List<MacMainpSbruanDinner> macMainpSbruanDinnerList = macMainpSbruanDinnerService
                .list(new QueryWrapper<MacMainpSbruanDinner>().lambda().eq(MacMainpSbruanDinner::getDeviceId, macMainpSbruan.getId()));
        for (MacMainpSbruanDinner goo : macMainpSbruanDinnerList) {
            if (DateUtil.hourMinuteBetween(hourMin, goo.getStartTime(), goo.getEndTime())) {
                return goo.getDinner();
            }
        }
        throw new Exception("未找到该灶类");
    }

    //上报方法
    private AlipayTradePayResponse havePost(String orders, String orderPrice,
                                            String authCode, String agreementNo,
                                            String fkPrice, String terminalParams, String aliToken) {
        try {
            AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do",
                    AliPayUtil.getAppid(), AliPayUtil.getPrivateKey(),
                    "json", "GBK", AliPayUtil.getPublicKey(),
                    "RSA2");
            AlipayTradePayRequest request = new AlipayTradePayRequest();
            JsonsRootBean jsonsRootBean;
            if (StringUtils.isEmpty(agreementNo)) {
                jsonsRootBean = new JsonsRootBean(orders, orderPrice,
                        authCode, AliPayUtil.getAssignJointAccountId(), fkPrice, terminalParams);
            } else {
                jsonsRootBean = new JsonsRootBean(orders, orderPrice,
                        authCode, agreementNo, AliPayUtil.getAssignJointAccountId(), fkPrice, terminalParams);
            }
            request.setBizContent(JSONObject.toJSONString(jsonsRootBean));
            return alipayClient.execute(request, null, aliToken);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
//
//    private void saveReserve(AliFaceOrders aliFaceOrders, Fk fk,
//                             MacMainpSbruan macMainpSbruan,
//                             String price, String sc) {
//
//        Reserve reserve = new Reserve();
//        reserve.setCardno(fk.getCardno());
//        reserve.setZl(macMainpSbruan.getZl());
//        reserve.setBqh(fk.getBqh());
//        reserve.setKsh(fk.getKsh());
//        reserve.setDinner(aliFaceOrders.getDinner());
//        reserve.setBed("0");
//        reserve.setPosnum(macMainpSbruan.getPos());
//        reserve.setDinner(aliFaceOrders.getDinner());
//        reserve.setCode(macMainpSbruan.getCode());
//        reserve.setSl(1);
//        reserve.setJe(price);
//        try {
//            reserve.setYe("0");
//        } catch (Exception e) {
//            reserve.setYe("0");
//        }
//        reserve.setKl(fk.getKl());
//        reserve.setSc(sc);
//        reserve.setLsh2(aliFaceOrders.getTradeNo());
//        reserve.setCzrq(new Date());
//        reserve.setDcrq(new SimpleDateFormat("yyyy-MM-dd 00:00:00").format(new Date()));
//        reserve.setHname("现金菜");
//        reserve.setSddz(aliFaceOrders.getDeviceId());
//        reserve.setCs(0);
//        reserve.setKehu(fk.getName());
//        reserve.setZfserialnumber(aliFaceOrders.getOrders());
//        reserve.setAddr(macMainpSbruan.getAddr());
//        reserveService.save(reserve);
//    }
}
